package com.jianyun.jyzs.activity.newsign;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.hannesdorfmann.mosby3.mvp.MvpActivity;
import com.jianyun.jyzs.R;
import com.jianyun.jyzs.adapter.NewSign2Adapter;
import com.jianyun.jyzs.adapter.TestAdaper;
import com.jianyun.jyzs.bean.NewSign2Bean;
import com.jianyun.jyzs.bean.Sign2Bean;
import com.jianyun.jyzs.bean.SignStateBean;
import com.jianyun.jyzs.common.CustomLinearLayoutManager;
import com.jianyun.jyzs.presenter.NewSign2Presenter;
import com.jianyun.jyzs.utils.DateUtils;
import com.jianyun.jyzs.utils.DeviceUtils;
import com.jianyun.jyzs.utils.FullDialogLoading;
import com.jianyun.jyzs.utils.LocationManager;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.NetUtil;
import com.jianyun.jyzs.utils.UtilsStyle;
import com.jianyun.jyzs.view.iview.INewSign2View;
import com.jrmf360.rylib.common.util.ToastUtil;
import com.longsh.optionframelibrary.OptionMaterialDialog;
import com.prolificinteractive.materialcalendarview.CalendarDay;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by yangshijun on 2018/7/30.
 */

public class NewSign2Activity extends MvpActivity<INewSign2View, NewSign2Presenter> implements INewSign2View
        , LocationManager.LocationManagerListener {

    @BindView(R.id.topBack)
    ImageView topBack;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.iv_calendar)
    ImageView ivCalendar;
    @BindView(R.id.top_rl)
    RelativeLayout topRl;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_now_time)
    TextView tvNowTime;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.tv_week)
    TextView tvWeek;

    private static final int msgKey1 = 1;
    SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
    private String enterpriseCode;
    private String userId;
    private NewSign2Adapter newSign2Adapter;
    private LocationManager locationManager;
    private String[] NETTYPE = {"定位失败", "GPRS", "前次定位结果", "缓存定位结果", "Wifi", "EDGE", "离线定位结果"};//网络类型
    public static int postion = -1;
    private List<NewSign2Bean.SignDetail> signDetail;
    private FullDialogLoading dialog;
    private OptionMaterialDialog mMaterialDialog;
    private TimeThread timeThread;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        UtilsStyle.setStatusBarMode(this, true);
        setContentView(R.layout.activity_new_sign_2);
        ButterKnife.bind(this);
        initView();
        initData();
    }

    @NonNull
    @Override
    public NewSign2Presenter createPresenter() {
        return new NewSign2Presenter();
    }

    private void initData() {
        long time = System.currentTimeMillis();
        Date date = new Date(time);
        tvNowTime.setText(format.format(date));
        timeThread = new TimeThread();
        timeThread.start();
        enterpriseCode = LoginCache.getInstance().getLoginCache().getEnterpriseCode();
        userId = LoginCache.getInstance().getUserInfo().getUserId();
        CalendarDay today = CalendarDay.today();
        tvWeek.setText(DateUtils.getWeek());
        String formatDate = DateUtils.getFormatDate(today);
        tvDate.setText(formatDate);
        getPresenter().getSign2List(enterpriseCode, userId, formatDate);
    }

    private void initView() {
        if (locationManager == null) {
            locationManager = new LocationManager(this);
        }
        dialog = FullDialogLoading.createDialog(this);
        dialog.setMessage("loading...");
        mMaterialDialog = new OptionMaterialDialog(this);
        recyclerView.setLayoutManager(new CustomLinearLayoutManager(this,
                LinearLayoutManager.VERTICAL, false));
        newSign2Adapter = new NewSign2Adapter(this);
        //TestAdaper testAdaper = new TestAdaper(this);
        recyclerView.setAdapter(newSign2Adapter);
        newSign2Adapter.setOnClickListener(new NewSign2Adapter.OnClickListener() {
            @Override
            public void onclick(int postion, NewSign2Bean.SignDetail signDetail) {
                NewSign2Activity.postion = postion;
                //定位
                locationManager.locationStart(NewSign2Activity.this);
                //先获取用户打卡状态
                dialog.show();
            }
        });
    }

    @OnClick({R.id.topBack, R.id.iv_calendar})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.topBack:
                finish();
                break;
            case R.id.iv_calendar:
                startActivity(new Intent(this, NewSignReCordActivity.class).putExtra("sign","sign2"));
                //finish();
                break;
        }
    }

    @Override
    public void onGetSignListSunccess(List<NewSign2Bean.SignDetail> signDetail) {
        this.signDetail = signDetail;
        Log.i("test", "打卡记录：" + signDetail.toString());
        newSign2Adapter.setSignDetail(signDetail);
    }

    @Override
    public void onSignSuccess(Sign2Bean sign2Bean) {
        if (sign2Bean.getResult()) {
            // if (postion!=-1){
            NewSign2Bean.SignDetail signDetail = this.signDetail.get(postion);
            signDetail.setSignTime(sign2Bean.getSignTime());
            signDetail.setIsShowSignStatusCode(sign2Bean.getIsShowSignStatusCode());
            signDetail.setSignAddress(sign2Bean.getSignAddress());
            signDetail.setSignStatusCode(sign2Bean.getSignStatusCode() + "");
            signDetail.setSignAddressStatusCode(sign2Bean.getSignAddressStatusCode() + "");
            signDetail.setSignId(sign2Bean.getSignId());
            //this.signDetail.add(postion,signDetail);
            newSign2Adapter.setSignDetail(this.signDetail);
//            }else{
//                NewSign2Bean.SignDetail signDetail = this.signDetail.get(postion);
//                //if (signDetail.getSignId().equals(sign2Bean.getSignId())){
//                    signDetail.setSignTime(sign2Bean.getSignTime());
//                    signDetail.setIsShowSignStatusCode(sign2Bean.getIsShowSignStatusCode());
//                    signDetail.setSignAddress(sign2Bean.getSignAddress());
//                    signDetail.setSignStatusCode(sign2Bean.getSignStatusCode()+"");
//                    signDetail.setSignAddressStatusCode(sign2Bean.getSignAddressStatusCode()+"");
//                    signDetail.setSignId(sign2Bean.getSignId());
//               // }
//            }


//            Intent intent = new Intent(this, NewSignSuccessActivity.class);
//            intent.putExtra("sign2Bean", sign2Bean);
//            startActivity(intent);
//            finish();
        } else {

        }
    }

    @Override
    public void onUpdateSignSuccess(Object o) {

    }

    @Override
    public void onGetSignState(SignStateBean signStateBean) {
        dialog.dismiss();
        int signStatusCode = signStateBean.getSignStatusCode();
        String mesg = "";
        if (2 == signStatusCode) {
            //迟到
            mesg = "迟到打卡,确定要打卡吗？";
            setDiolag(mesg);
        } else if (3 == signStatusCode) {
            //早退
            mesg = "早退打卡,确定要打卡吗？";
            setDiolag(mesg);
        } else if (1 == signStatusCode) {
            locationManager.locationStart(this);
            dialog.show();

        }
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {
        dialog.dismiss();
    }

    @Override
    public void onFaile(String msg) {
        ToastUtil.showToast(this, msg);
    }

    @Override
    public void locationResult(boolean result, AMapLocation aMapLocation) {
        if (!result) {
            ToastUtil.showToast(this, "定位失败！");
        } else {
            if (signDetail != null) {
                NewSign2Bean.SignDetail signDetail = this.signDetail.get(postion);
                String signId = signDetail.getSignId();
                //判定是否重新打卡
                if (signId != null && !TextUtils.isEmpty(signId)) {
                    HashMap<String, String> updateSign = updateSign(aMapLocation);
                    updateSign.put("signId", signId);
                    getPresenter().updateSign2(updateSign);
                } else {
                    String workTime = signDetail.getWorkTime();
                    String signType = signDetail.getWorkType();
                    String bcDate = signDetail.getBcDate();
                    HashMap<String, String> hashMap = signPamars(aMapLocation);
                    hashMap.put("signType", signType);
                    hashMap.put("workTime", workTime);
                    hashMap.put("bcDate", bcDate);
                    getPresenter().startSign2(hashMap);
                }

            }

        }
    }

    public void setDiolag(String msg) {
        mMaterialDialog
                .setMessage(msg)
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //再次开始定位
                        locationManager.locationStart(NewSign2Activity.this);
                        mMaterialDialog.dismiss();
                        dialog.show();

                    }
                }).setNegativeButton("取消",
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mMaterialDialog.dismiss();
                    }
                })
                .setCanceledOnTouchOutside(true)
                .setOnDismissListener(
                        new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                //对话框消失后回调
                            }
                        }).show();

    }

    public class TimeThread extends Thread {
        @Override
        public void run() {
            super.run();
            do {
                try {
                    Thread.sleep(1000);
                    Message msg = new Message();
                    msg.what = msgKey1;
                    mHandler.sendMessage(msg);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while (true);
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case msgKey1:
                    long time = System.currentTimeMillis();
                    Date date = new Date(time);
                    tvNowTime.setText(format.format(date));
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 销毁线程方法
     */
    private void destroyThread() {
        try {
            if (null != timeThread && Thread.State.RUNNABLE == timeThread.getState()) {
                try {
                    Thread.sleep(500);
                    timeThread.interrupt();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            timeThread = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyThread();
    }

    /**
     * 第一次打卡
     *
     * @param aMapLocation
     * @return
     */
    public HashMap<String, String> signPamars(AMapLocation aMapLocation) {
        //30.467963#longitude=114.417801
        HashMap<String, String> map = new HashMap<>();
        map.put("method", "Sign");
        map.put("enterpriseCode", enterpriseCode);
        map.put("employeeId", userId);
        String LOCATION_X = aMapLocation.getLongitude() + "";
        String LOCATION_Y = aMapLocation.getLatitude() + "";
        map.put("location_X", LOCATION_X);
        map.put("location_Y", LOCATION_Y);
        map.put("scale", "5");
        String label = aMapLocation.getProvince() + aMapLocation.getCity() + aMapLocation.getDistrict() + aMapLocation.getStreet();
        map.put("label", label);
        String deviceId = DeviceUtils.getAndroidID(this);
        map.put("deviceId", deviceId);
        map.put("netType", NETTYPE[aMapLocation.getLocationType()]);
        map.put("platFormInfo", "android");
        map.put("userIp", NetUtil.getLocalIpAddress());
        map.put("sourceSystem", "jyzs");
        //打卡类型
        //map.put("signType", signTypes);
        return map;
    }

    /**
     * 更新打卡
     *
     * @param aMapLocation
     * @return
     */
    public HashMap<String, String> updateSign(AMapLocation aMapLocation) {
        HashMap<String, String> map = new HashMap<>();
        map.put("method", "UpdateSign");
        map.put("enterpriseCode", enterpriseCode);
        map.put("employeeId", userId);
        String LOCATION_Y = aMapLocation.getLatitude() + "";
        String LOCATION_X = aMapLocation.getLongitude() + "";
        map.put("location_X", LOCATION_X);
        map.put("location_Y", LOCATION_Y);
        String label = aMapLocation.getProvince() + aMapLocation.getCity() + aMapLocation.getDistrict() + aMapLocation.getStreet();
        map.put("signAddress", label);
        return map;
    }
}
